package cn.openea.perpartner.payment.web.subpoints.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.convert.Convert;
import cn.openea.perpartner.common.core.utils.Arith;
import cn.openea.perpartner.payment.web.subpoints.entity.SubPoint;
import cn.openea.perpartner.payment.web.subpoints.dto.SubPointDto;
import cn.openea.perpartner.payment.web.subpoints.mapper.SubPointMapper;
import cn.openea.perpartner.payment.web.subpoints.service.ISubPointService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * (SubPaymentUserscore)表服务实现类
 *
 * @author makejava
 * @since 2022-06-27 14:45:53
 */
@Service("subPaymentPointsService")
public class SubPointServiceImpl extends ServiceImpl<SubPointMapper, SubPoint> implements ISubPointService {
    private final String TYPEOFSUB = "sub";
    private final String TYPEOFADD = "add";

    @Override
    public SubPoint selectPointsByUserId(String userId, String sceneId) {
        LambdaQueryWrapper<SubPoint> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SubPoint::getUserid, userId);
        wrapper.eq(SubPoint::getSceneId, sceneId);
        return this.getOne(wrapper);
    }

    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    @Override
    public boolean updateByUserId(SubPointDto paymentDto, String operType) {
        LambdaQueryWrapper<SubPoint> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SubPoint::getUserid, paymentDto.getUserId());
        wrapper.eq(SubPoint::getSceneId, paymentDto.getSceneId());
        SubPoint paymentPoints = this.getOne(wrapper);
        if (BeanUtil.isEmpty(paymentPoints) && TYPEOFADD.equals(operType)) {
            paymentPoints = new SubPoint();
            paymentPoints.setUserid(paymentDto.getUserId());
            paymentPoints.setPoints(paymentDto.getPoints());
            paymentPoints.setSceneId(paymentDto.getSceneId());
            return this.save(paymentPoints);
        }
        if (BeanUtil.isEmpty(paymentPoints) && TYPEOFSUB.equals(operType)) {
            return false;
        }
        double allPoint = Convert.toDouble(paymentPoints.getPoints());
        double editPoint = Convert.toDouble(paymentDto.getPoints());
        if (TYPEOFADD.equals(operType)) {
            double newPoint = Arith.add(allPoint, editPoint);
            paymentPoints.setPoints(Arith.format(newPoint));
        }
        if (TYPEOFSUB.equals(operType) && allPoint < editPoint) {
            return false;
        }
        if (TYPEOFSUB.equals(operType)) {
            double newPoint = Arith.sub(allPoint, editPoint);
            paymentPoints.setPoints(Arith.format(newPoint));
        }
        return this.saveOrUpdate(paymentPoints);
    }

}
